let _Vue = null

export default class HashRouter {
  static install (Vue) {
    // 保证当前插件只被安装一次
    this.installed ?? (this.installed = true)
    _Vue = Vue
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router)  {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  constructor (options) {
    this.options = options
    this.data = _Vue.observable({
      current: '/'
    })
    this.routeMap = {}
  }
  init () {
    this.createRouteMap()
    this.initCompoent(_Vue)
    this.initEvent()
  }

  // 创建路由映射
  createRouteMap () {
    if (this.options.routes) {
      this.options.routes.forEach(item => {
        this.routeMap[item.path] = item.component
      })
    }
  }

  // 创建 router-link\router-view 组件
  initCompoent (Vue) {
    Vue.component("router-link", {
      props: {
        to: String
      },
      render(h) {
        return h('a', {
          attrs: {
            href: `#${this.to}`
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          window.location.hash = `#${this.to}`
          this.$router.data.current = this.to

          e.preventDefault()
        }
      }
    })

    const _this = this
    _Vue.component("router-view", {
      render (h) {
        // h方法可以直接传入一个组件
        console.log(_this.data.current)
        return h(_this.routeMap[_this.data.current])
      }
    })
  }

  // 监听hashChange事件，实现组件视图更新
  initEvent () {
    window.addEventListener('hashchange', () => {
      let hash = window.location.hash
      this.data.current = hash.replace('#', '')
    })
  }
}